﻿using Library.Entity;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Wallpaper.Models.Entities;
using Wallpaper.Services.IService;

namespace Wallpaper.Services.Service
{
    public class JwtService : IJwtService
    {
        private readonly JwtOpt _jwtOptions;

        public JwtService(IOptions<JwtOpt> jwtOptions)
        {
            _jwtOptions = jwtOptions.Value;
        }


        /// <summary>
        /// 生成管理员的JWT
        /// </summary>
        /// <param name="admin"></param>
        /// <returns></returns>
        /// <summary>
        /// 生成管理员的JWT
        /// </summary>
        /// <param name="admin"></param>
        /// <returns></returns>
        public string GenerateAdminToken(Admin admin, string roleCode)
        {
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtOptions.SecurityKey));
            var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var claims = new List<Claim>
            {
                new Claim(JwtRegisteredClaimNames.Sub, admin.Id),
                new Claim("account", admin.Account ?? ""),
                new Claim("type", "admin"), // 用户类型  
            };
            // 核心修正：为 roleCode Claim 指定名称，这里使用 "roles"
            if (!string.IsNullOrEmpty(roleCode))
            {
                claims.Add(new Claim(ClaimTypes.Role, roleCode));
            }
            var token = new JwtSecurityToken(
                issuer: _jwtOptions.Issuer,
                audience: _jwtOptions.Audience,
                claims: claims,
                expires: DateTime.UtcNow.AddMinutes(_jwtOptions.ExpiresMinutes),
                signingCredentials: credentials
            );
            return new JwtSecurityTokenHandler().WriteToken(token);
        }

        /// <summary>
        /// 生成JWT
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public string GenerateToken(User user)
        {
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtOptions.SecurityKey));
            var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var claims = new[]
            {
            new Claim(JwtRegisteredClaimNames.Sub, user.Id),
            new Claim(JwtRegisteredClaimNames.UniqueName, user.OpenId),
            new Claim(JwtRegisteredClaimNames.Iat, DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64), // 签发时间
            new Claim("nickname", user.Nickname ?? ""),
            new Claim("avatar", user.AvatarUrl ?? ""),
            new Claim("type", "user")  
        };

            var token = new JwtSecurityToken(
                issuer: _jwtOptions.Issuer,
                audience: _jwtOptions.Audience,
                claims: claims,
                expires: DateTime.UtcNow.AddDays(_jwtOptions.RefreshExpiresDays), // 只修改这一行
                signingCredentials: credentials
            );

            return new JwtSecurityTokenHandler().WriteToken(token);
        }
    }

}
